package pl.edu.agh.mobilne;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.PorterDuff;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MedicalDevDataReciver extends Activity {
	
	private static final String APPLICATION_URI = "http://192.168.1.101:3000/resultsws";
	
	private Scheduler scheduler = new Scheduler();
	private List<String> results = new ArrayList<String>();
	NotificationManager nf = null;
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) { 	
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        nf = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        
        setSchedule();
        
        
        Button measureBloodPressureBt = (Button) findViewById(R.id.BloodPresureBtn);
        measureBloodPressureBt.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
        measureBloodPressureBt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	((Button) view.findViewById(R.id.BloodPresureBtn)).getBackground().setColorFilter(0xFF808080, PorterDuff.Mode.MULTIPLY);
            	Intent i = new Intent();
            	i.setAction( "pl.edu.agh.mobilne.measure");
            	i.setData(Uri.parse("bp://"));
          	    startActivityForResult(i,1);
     		}
        });
		
        Button measureWeightBt = (Button) findViewById(R.id.WeightBtn);
        measureWeightBt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	((Button) view.findViewById(R.id.WeightBtn)).getBackground().setColorFilter(0xFF808080, PorterDuff.Mode.MULTIPLY);
            	Intent i = new Intent();
            	i.setAction( "pl.edu.agh.mobilne.measure");
            	i.setData(Uri.parse("wght://"));
          	    startActivityForResult(i,1);
     		}
        });
        
        Button measureGlucoseBt = (Button) findViewById(R.id.GlucoseBtn);
        measureGlucoseBt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	((Button) view.findViewById(R.id.GlucoseBtn)).getBackground().setColorFilter(0xFF808080, PorterDuff.Mode.MULTIPLY);
            	Intent i = new Intent();
            	i.setAction( "pl.edu.agh.mobilne.measure");
            	i.setData(Uri.parse("gluc://"));
          	    startActivityForResult(i,1);
     		}
        });
        
        Button takePillsBt = (Button) findViewById(R.id.PillsBtn);
        takePillsBt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	((Button) view.findViewById(R.id.PillsBtn)).getBackground().setColorFilter(0xFF808080, PorterDuff.Mode.MULTIPLY);
            	//TODO
     		}
        });
		
        Button sendBt = (Button) findViewById(R.id.SendBtn);
        sendBt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	((Button) view.findViewById(R.id.SendBtn)).getBackground().setColorFilter(0xFF808080, PorterDuff.Mode.MULTIPLY);
            	for(String r : results){
            		String [] result = r.split(";");
            		putResult(result[0], result[1], result[2], result[3]);	
            	}
            	results.clear();

                /*int closeNotifyId = getIntent().getIntExtra( "notification_id", 0 );
                if ( closeNotifyId != 0 ){
                    nf.cancel( closeNotifyId );
                }*/
     		}
        });
        
        Button updateBt = (Button) findViewById(R.id.UpdateBtn);
        updateBt.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
            	scheduler.update(getApplicationContext());
     		}
        });
        
        //set buttons icons
        String todos = getIntent().getStringExtra("scenario");
        if (todos != null ){
            String [] todoArr = todos.split(";");
            for(int i=0; i<todoArr.length; i++){
            	if(todoArr[i].equals("BP"))
            		measureBloodPressureBt.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
            	else if(todoArr[i].equals("Weight"))
            		measureWeightBt.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
            	else if(todoArr[i].equals("Glucose"))
            		measureGlucoseBt.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
            	else if(todoArr[i].equals("Pills"))
            		takePillsBt.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
            	else if(todoArr[i].equals("Send"))
            		sendBt.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
            }
        }

    }
    
    private void setSchedule() {
		SharedPreferences settings = getSharedPreferences(Scheduler.PREFS_NAME, 0);
        String schedule = settings.getString("schedule", null);
		if(schedule != null){
			scheduler.parse(getApplicationContext(), schedule);
		}
		else{
			scheduler.update(getApplicationContext());
		}
			
	}

	@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        switch (requestCode) {
	        case 1:
	        	Integer result = Integer.parseInt(data.getStringExtra("result"));
	        	String measurementName = data.getStringExtra("measurementName");
	        	results.add(new Integer(new Random().nextInt()).toString() +";"+ measurementName +";"+ result.toString() + ";" + "date");
	            break;
	         
	        default:
	            break;
        }
    }
    
    public static String getResultsUri(String meaurementID) {
        return APPLICATION_URI + "/results/" + meaurementID;
    }
    
    public static void putResult(String id, String measurementName, String result, String date) {

   		DefaultHttpClient httpclient = new DefaultHttpClient();
   		HttpPost request = new HttpPost("http://10.0.2.2:8080/blog/results/new");
   		try {
   			
    		//TODO	
   			List<NameValuePair> formparams = new ArrayList<NameValuePair>();
   			formparams.add(new BasicNameValuePair("patientID", "Steven"));
   			formparams.add(new BasicNameValuePair("name", measurementName));
   			formparams.add(new BasicNameValuePair("value",result));
   			formparams.add(new BasicNameValuePair("timestamp", date));
   			formparams.add(new BasicNameValuePair("measurementID", id));
    			
   			UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
   			request.setEntity(entity);
   			HttpResponse response = httpclient.execute(request);			
   			response.getEntity().writeTo(System.out);
    			
   		} catch (ClientProtocolException e) {
   			e.printStackTrace();
   		} catch (IOException e) {
   			e.printStackTrace();
   		}
    		
    }

}